package com.xhu.controller;

import com.xhu.entity.User;
import com.xhu.service.HideService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class HideController {

    @Value("${conf.filePath}")
    private String filePath;

    @Value("${conf.webAddress}")
    private String webAddress;

    @Autowired
    private HideService hideService;

    @Autowired
    private HttpSession session;

    @PostMapping("/doHideByAttr")
    public String doHideByAttr(String missionName, String encryptContext, MultipartFile file){
        String result;

        //判断文件大小是否为空
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        //在session中获取用户所有信息
        String path = filePath + "/" +UUID.randomUUID().toString() + file.getOriginalFilename();
        File dest = new File(path);
        try {
            //储存文件到本地
            file.transferTo(dest);
            //做信息隐藏
            result = hideService.hideMessageByAttr(((User) session.getAttribute("userInfo")).getUserAccount()
                    , missionName,path, encryptContext);
        } catch (IOException e) {
            result = "false";
            e.printStackTrace();
        }

        return result;
    }

    @PostMapping("/doHide")
    public String doHide(String missionName, String encryptContext,String type, MultipartFile file){
        String result = "true";

        //判断文件大小是否为空
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        //在session中获取用户所有信息
        User userInfo = (User) session.getAttribute("userInfo");
        String userAccount = userInfo.getUserAccount();

        //设置随机文件名
        String fileName = UUID.randomUUID().toString() + file.getOriginalFilename();
        String totalPath = filePath + "/" + fileName;
        File dest = new File(totalPath);
        try {
            //储存文件到本地
            file.transferTo(dest);
            //做信息隐藏
            result = hideService.hideMessage(userAccount, missionName,totalPath, encryptContext, type);
        } catch (IOException e) {
            result = "false";
            e.printStackTrace();
        }

        return result;
    }

    @GetMapping("/missionIsExist")
    public boolean missionIsExist(String missionName){
        //在session中获取用户所有信息
        User userInfo = (User) session.getAttribute("userInfo");
        String userAccount = userInfo.getUserAccount();

        return hideService.checkMission(userAccount, missionName);
    }
}
